<template>
  <div class="table-page-container layout-padding">
    <el-card shadow="hover" class="layout-padding-auto">
      <div class="system-user-search mb15">
        <el-form ref="searchFormRef" :model="searchForm" inline>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="searchForm.name" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="searchForm.mobile" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button size="default" type="primary" @click="refresh">
              <el-icon>
                <ele-Search/>
              </el-icon>
              查询
            </el-button>
            <el-button size="default" @click="onReset">
              <el-icon>
                <ele-RefreshRight/>
              </el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table
        :data="tableData.list"
        v-loading="loading"
        element-loading-text="加载中"
        border
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center"/>
        <el-table-column prop="nick_name" label="用户昵称"></el-table-column>
        <el-table-column label="头像">
          <template #default="{ row }">
            <el-image :src="row.avatar" style="width: 60px; height: 60px"/>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="用户姓名"></el-table-column>
        <el-table-column prop="mobile" label="手机号"></el-table-column>
        <el-table-column prop="uid" label="用户UID"></el-table-column>
        <el-table-column prop="gender" label="性别">
          <template #default="{ row }">
            <el-tag v-if="row.gender === 'MALE'" type="primary">男</el-tag>
            <el-tag v-else-if="row.gender === 'FEMALE'" type="danger">女</el-tag>
            <el-tag v-else type="info">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="last_login_date" label="上次登陆时间">
          <template #default="{ row }">
            {{ formatDate(row.last_login_date, 'time') }}
          </template>
        </el-table-column>
        <el-table-column prop="is_distributor" align="center" label="渠道商">
          <template #default="{ row }">
           {{ row.distributor ? '是': '否' }}
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="160">
          <template #default="scope">
            <el-button
              v-if="$can(ButtonPermission.UPDATE_WEAPP_USER)"
              size="small"
              text
              type="primary"
              @click="handleViewQrcode(scope.row)"
            >二维码
            </el-button
            >
            <el-button
              v-if="$can(ButtonPermission.DELETE_WEAPP_USER)"
              size="small"
              text
              type="primary"
              @click="handleDelete(scope.row)"
              style="color: red"
            >删除
            </el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <CommonPagination :pagination="pagination" :total="tableData.total"></CommonPagination>
      <el-dialog title="用户二维码" v-model="showQrDialog" width="400">
        <div style="width: 200px; margin: 0 auto">
          <img :src="qrcodeSrc" style="width: 200px;height: 200px;"/>
          <el-button
            type="primary"
            plain
            style="margin-top: 20px; width: 100%"
            @click="handleDownload"
          >下载
          </el-button
          >
        </div>
      </el-dialog>

    </el-card>

  </div>
</template>

<script setup lang="ts" name="weappUser">
import { reactive, ref } from 'vue';
import { ElMessageBox, ElMessage, FormInstance } from 'element-plus';
import { readAllWeappUser, deleteWeappUser, getQrcode } from '/@/api/weapp-user';
import { useTable } from '/@/hooks/use-table';
import CommonPagination from '/@/components/common-pagination/index.vue';
import { ButtonPermission } from '/@/constants';
import { formatDate } from '/@/utils';
import { readDistributor } from "/@/api/distributor";

const qrcodeSrc = ref();
const searchFormRef = ref<FormInstance>();

const searchForm = reactive({
  name: undefined,
  mobile: undefined
});
const showQrDialog = ref(false);


const { tableData, loading, pagination, refresh } = useTable<any>(({ page, pageSize }) =>
  readAllWeappUser({ page, pageSize, ...searchForm }).then(({ data }) => {
    return {
      total: data?.total,
      list: data?.list
    };
  })
);

const onReset = () => {
  searchFormRef.value?.resetFields();
  refresh();
};

const handleDelete = (row: any) => {
  ElMessageBox.confirm(`此操作不可恢复，是否继续?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    buttonSize: 'default',
    beforeClose: async (action, instance, done) => {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true;
        instance.confirmButtonText = '提交中';
        await deleteWeappUser(row.id).then(() => {
          ElMessage.success('删除成功');
          refresh();
        });

        instance.confirmButtonLoading = false;
        done();
      } else {
        done();
      }
    }
  });
};

const handleViewQrcode = (row: any) => {
  getQrcode(row.id).then((res: any) => {
    if (res.type === 'application/json') {
      ElMessage.error('获取二维码失败');
      return
    }
    const url = URL.createObjectURL(res);
    qrcodeSrc.value = url
    showQrDialog.value = true;
  });
};

const handleDownload = () => {
  // 创建一个下载链接
  const downloadLink = document.createElement('a');
  downloadLink.href = qrcodeSrc.value;
  downloadLink.download = '用户二维码.png'; // 设置下载的文件名

  // 模拟点击这个链接，触发下载
  document.body.appendChild(downloadLink);
  downloadLink.click();
  downloadLink.remove();
};
</script>
